import { ApiBody } from "@/types/api_body";

export async function api_base({ url, method, body = null }: ApiBody) {
  const URL = `${process.env.NEXT_PUBLIC_API_URL}${url}`;

  const requestOptions: RequestInit = {
    method: method,
    headers: {
      "Content-Type": "application/json",
    },
  };

  // 只有当 body 不为 null 时才添加 body
  if (body !== null) {
    requestOptions.body = JSON.stringify(body);
  }

  try {
    const res = await fetch(URL, requestOptions);

    if (!res.ok) {
      console.log(`请求错误: ${res.status}`);
      throw res.status;
    }

    return res.json();
  } catch (err) {
    console.log(`请求错误：${err}`);
    throw err;
  }
}
